var app = getApp();
var ImageURL = app.globalData1.ImageURL;
var hostURL = app.globalData1.hostURL;
var Bmob = require('../../utils/bmob.js');
var utils = require('../../utils/util.js');
const AV = require('../../utils/av-weapp.js')
var tcity = require("../../utils/citys.js");

//var app = getApp();
var that;
var i=0;
Page({
   data: {
    
      provinces: [],
      province: "",
      citys: [],
      city: "",
      countys: [],
      county: '',
      value: [0, 0, 0],
      values: [0, 0, 0],
      condition: false,

      addressName: '',
      addressDetail: '',
      latitude: '',
      longitude: '',

     pics: [],
     img_arr: [],
     imagePath: [],

      images: ''  ,
      inputText: '',
      images: [],
      uploadedImages: [],
      mageWidth: getApp().screenWidth / 4 - 10,
      address:[],

    

      router: [],//保存一级分类和二级分类
      sg: [],//保存二级分类中的名称
      rs: [],
      cg1: [],//保存选中的一级分类中的二级分类
      brandindex: '',
      index1: '',
      sort_id: '',//一级分类id
      category_id: '',//二级分类id

      inputAddress: '',

      //pics:[]
      major:'',
      telephone:'',
      score:'',
      salary:'',
      money:'',
      remark:'',
      addressName:''
      
   
   },
   onLoad: function () {
 
      that = this;

      tcity.init(that);
      var cityData = that.data.cityData;
      const provinces = [];
      const citys = [];
      const countys = [];
      for (let i = 0; i < cityData.length; i++) {
         provinces.push(cityData[i].name);
      }
      console.log('省份完成');
      for (let i = 0; i < cityData[0].sub.length; i++) {
         citys.push(cityData[0].sub[i].name)
      }
      console.log('city完成');
      for (let i = 0; i < cityData[0].sub[0].sub.length; i++) {
         countys.push(cityData[0].sub[0].sub[i].name)
      }
      that.setData({
         'provinces': provinces,
         'citys': citys,
         'countys': countys,
         'province': cityData[0].name,
         'city': cityData[0].sub[0].name,
         'county': cityData[0].sub[0].sub[0].name
         
      })
      console.log('初始化完成');



     // var that = this
      wx.request({
         url: hostURL + 'sharedplatform-web/assortment/findAssortment.action',
      //   url: 'http://193.112.68.182:8090/sharedplatform-web/assortment/findAssortment.action',
         method: 'GET',
         data: {},
         header: {
            'Accept': 'application/json'
         },
         success: function (res) {

            var router = []
            router = res.data.assortmentList
            var cg = []
            var rs = []
            for (var i = 0; i < router.length; i++) {
               cg.push(router[i].categoryList)
               rs.push(router[i].sort_name)
               console.log(router[i].categoryList)
            }
            that.setData({
               router: res.data.assortmentList,
               rs: rs
            })
         }
      })

   },

   bindPickerChange0: function (e) {
      this.setData({
         brandindex: e.detail.value,
         index1: ''
      })
      var rt = []
      rt = this.data.router
      var cg1 = []

      cg1.push(rt[this.data.brandindex].categoryList)
      var sg = []
      for (var j = 0; j < cg1[0].length; j++) {
         sg.push(cg1[0][j].category_name)
      }
      this.setData({
         sg: sg,
         cg1: cg1
      })
   },
   bindPickerChange1: function (e) {
      this.setData({
         index1: e.detail.value
      })
      var cg1 = []
      cg1 = this.data.cg1
      var category_id = cg1[0][this.data.index1].id
      var sort_id = cg1[0][this.data.index1].sort_id
      console.log(category_id)
      console.log(sort_id)
      this.setData({
         category_id: category_id,
         sort_id: sort_id
      })

   },


   bindChange: function (e) {
      //console.log(e);
      var val = e.detail.value
      var t = this.data.values;
      var cityData = this.data.cityData;

      if (val[0] != t[0]) {
         console.log('province no ');
         const citys = [];
         const countys = [];

         for (let i = 0; i < cityData[val[0]].sub.length; i++) {
            citys.push(cityData[val[0]].sub[i].name)
         }
         for (let i = 0; i < cityData[val[0]].sub[0].sub.length; i++) {
            countys.push(cityData[val[0]].sub[0].sub[i].name)
         }

         this.setData({
            province: this.data.provinces[val[0]],
            city: cityData[val[0]].sub[0].name,
            citys: citys,
            county: cityData[val[0]].sub[0].sub[0].name,
            countys: countys,
            values: val,
            value: [val[0], 0, 0]
         })
         //  console.log( province + city + county)
         return;
      }
      if (val[1] != t[1]) {
         console.log('city no');
         const countys = [];

         for (let i = 0; i < cityData[val[0]].sub[val[1]].sub.length; i++) {
            countys.push(cityData[val[0]].sub[val[1]].sub[i].name)
         }

         this.setData({
            city: this.data.citys[val[1]],
            county: cityData[val[0]].sub[val[1]].sub[0].name,
            countys: countys,
            values: val,
            value: [val[0], val[1], 0]
         })
         return;
      }
      if (val[2] != t[2]) {
         console.log('county no');
         this.setData({
            county: this.data.countys[val[2]],
            values: val
         })
         return;
      }
   },

   open: function () {
      this.setData({
         condition: !this.data.condition
      })
   },



   inputMajorRight: function (e) {
      this.setData({
         major:e.detail.value,
      })
      var major = []
      major = this.data.major
      if (!e.detail.value) {
         wx.showToast({
            title: '物品名称不能为空',
         })  
         this.setData({
            inputMajor: false
         })
      }
      else {
         this.setData({
            inputMajor: true,
            major: major
         })
         console.log(major)
      }
   },

   inputTelephoneRight: function (e) {
      this.setData({
         telephone: e.detail.value,
      })
      var telephone = []
      telephone = this.data.telephone
      if (!e.detail.value) {
         wx.showToast({
            title: '手机号不能为空',
         })  
         this.setData({
            inputTelephone: false
         })
         return false 

      }
      else {
          
         var phonetel = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1})|(17[0-9]{1}))+\d{8})$/;
         var myreg = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1})|(17[0-9]{1}))+\d{8})$/;
         if (!myreg.test(telephone)) {
            wx.showToast({
               title: '手机号有误！',
               icon: 'success',
               duration: 1500
            })
            return false;
         }
         this.setData({
            inputTelephone: true,
            telephone: telephone
         })
         return true
      }
   },

   inputScoreRight: function (e) {
      this.setData({
         score: e.detail.value,
      })
      var score = []
      score = this.data.score
      if (!e.detail.value) {
         wx.showToast({
            title: '数量不能为空',
         })  
         this.setData({
            inputScore: false
         })
      }
      else {
         //^[0-9]*[1-9][0-9]*$　
         var regNum = new RegExp('^[0-9]*[1-9][0-9]*$', 'g'); 
         if (!regNum.test(score)) {
            wx.showToast({
               title: '数量有误！',
               icon: 'success',
               duration: 1500
            })
            return false;
         }
         this.setData({
            inputScore: true,
            score: score
         })
         console.log(score)  
      }
   },

   inputSalaryRight: function (e) {
      this.setData({
         salary: e.detail.value,
      })
      var salary= []
      salary = this.data.salary
      if (!e.detail.value) {
         wx.showToast({
            title: '租用价格不能为空',
         })  
         this.setData({
            inputSalary: false
         })
      }
      else {
         var regNum = new RegExp('^(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*))$', 'g');
         if (!regNum.test(salary)) {
            wx.showToast({
               title: '租用价格有误！',
               icon: 'success',
               duration: 1500
            })
            return false;
         }
         this.setData({
            inputSalary: true,
            salary: salary
         })
         console.log(salary)  
      }
   },

   inputMoneyRight: function (e) {
      this.setData({
         money: e.detail.value,
      })
      var money = []
      money = this.data.money
      if (!e.detail.value) {
         wx.showToast({
            title: '押金不能为空',
         })  
         this.setData({
            inputMoney: false
         })
      }
      else {
         var regNum = new RegExp('^(([0-9]+\.[0-9]*[1-9][0-9]*)|(0)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*))$', 'g');
         if (!regNum.test(money)) {
            wx.showToast({
               title: '押金有误！',
               icon: 'success',
               duration: 1500
            })
            return false;
         }

         this.setData({
            inputMoney: true,
            money: money
         })
         
          console.log(money)  
      }
   },


   inputRemark: function (e) {
      this.setData({
         remark: e.detail.value,
      })
      var remark = []
      remark = this.data.remark
         this.setData({
            remark: remark
         })
         console.log(remark)  
   },
   inputAddressNameRight: function (e) {
      this.setData({
         addressName: e.detail.value,
      })
       var addressName = []
       addressName = this.data.addressName
       this.setData({
         addressName: addressName
       })
      console.log(e.detail.value)
   },

   

   // inputAddress: function (e) {
   //    this.setData({
   //       addressName: e.detail.value,
   //    })
   //    var addressName = []
   //    addressName = this.data.addressName
   //    if (!e.detail.value) {
   //       this.setData({
   //          inputAddress: false
   //       })
   //    }
   //    else {
   //       this.setData({
   //          inputAddress: true,
   //          addressName: addressName
   //       })
   //       console.log(addressName)
   //    }
   // },



  
   formReset: function (e) {
      console.log('form发生了reset事件，携带数据为：', e.detail.value)
      this.setData({
         chosen: ''
      })
   },

   jumpStudent: function () {
      wx.redirectTo({
         url: '../student-register/student-register'
      })
   },
  


   upconfirm: function () {
      if (app.globalData2.hasLogin) {
         wx.navigateTo({ url: "/pages/publish/publish" });
      }
      else {
         wx.navigateTo({ url: "/pages/ucenter/login/login" });
         return;
      }
     this.up();
   },
   up: function () {
     var that = this;
     // data = {
     //   // openid: app.openid,
     //   // program_id: app.program_id,
     //   // only_num: only_num
     // }
     wx.uploadFile({
       url: hostURL +'sharedplatform-web/publish/wx_upload.action',
       filePath: that.data.img_arr[i],
       name: 'image', //文件对应的参数名字(key)  
       // formData: data,  //其它的表单信息  
       success: function (res) {
       },
       complete: function (complete) {
         var cur_data = JSON.parse(complete.data)
         console.log(cur_data)
         var errno = cur_data.errno
         console.log(errno)
         if (errno == 0) {
           var path = cur_data.fileName
           that.setData({
             imagePath: that.data.imagePath.concat(path)
           })
         }
         // console.log(complete)
         i++
         if (i == that.data.img_arr.length) {
           // console.log(that.data.imagePath)
           console.log("提交完毕")


           var it=that
           //一级分类
           var sort_id = it.data.sort_id;
           //二级分类
           var category_id = it.data.category_id;
           var major = it.data.major;
           var telephone = it.data.telephone;
           var score = it.data.score;
           var salary = it.data.salary;
           var money = it.data.money;
           var remark = it.data.remark;
           var img_arr = it.data.img_arr;

           var province = it.data.province;
           var city = it.data.city;
           var county = it.data.county;
           var addressName = it.data.addressName;


           console.log(major)
           console.log(telephone)
           console.log(score)
           console.log(salary)
           console.log(money)
           console.log(remark)
           console.log(img_arr)
           console.log(province)
           console.log(city)
           console.log(county)
           console.log(addressName)
           

           wx.request({
              url: hostURL +"sharedplatform-web/publish/publishSource.action",
              data:
              {
                 sort_id: it.data.sort_id,//一级目录
                 category_id: it.data.category_id,//二级目录
                 img_arr: it.data.imagePath,//图片
                 major: it.data.major,//名称
                 telephone: it.data.telephone,//电话
                 score: it.data.score,//数量
                 salary: it.data.salary,//价格
                 money: it.data.money,//租金
                 remark: it.data.remark,//描述
                
                 province: it.data.province,
                 city: it.data.city,
                 county: it.data.county,
                 addressName: it.data.addressName,
                 user_id: app.globalData2.userid
              },
              method: 'Post', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
              header: {
                 'content-type': 'application/x-www-form-urlencoded; charset=UTF-8'
              },

              success: function (res) {
                 var err = res.data.success
                 //var usersend = res.data.usersend
                 if (err == "success") {
                    console.log(res.date)
                    //app.globalData2.hasLogin = true;
                   //wx.setStorageSync('usersend', res.data.usersend);
                  //   console.log(usersend),
                  //      wx.setStorage({
                  //         key: "usersend",
                  //         data: res.data.usersend,
                  //         //success: function () {
                  //      });
                             wx.showToast({
                                title: '提示信息',
                                content: '恭喜您发布成功',
                                showCancel: false
                             }),
                                wx.switchTab({
                                url: '/pages/index/index',
                                
                                    success:function(e)
                                    {
                                       var page = getCurrentPages().pop();
                                       if (page == undefined || page == null) return;
                                       page.onLoad()
                                    }


                                });
                          //}

                      
                 }
                 else {
                    wx.showToast({
                       title: '请补全发布信息',
                       content: '',
                    })
                  //   it.setData({
                  //      error: err
                  //   })
                 }
              },
              fail: function () {
                 console.log("请求失败！")
              },
           })

         } else if (i < that.data.img_arr.length) {//若图片还没有传完，则继续调用函数  
           that.up()
         }

       }
     })
   },


   upimg: function () {
     var that = this;
     if (this.data.img_arr.length < 12) {
       wx.chooseImage({
         sizeType: ['original', 'compressed'],
         sourceType: ['album', 'camera'],
         success: function (res) {
           that.setData({
             img_arr: that.data.img_arr.concat(res.tempFilePaths)
           })
           // var num = that.data.img_arr.length
         }
       })
     } else {
       wx.showToast({
         title: '最多上传12张图片',
         icon: 'loading',
         duration: 3000
       });
     }
   },  
   previewImage: function () {        // 预览图集
     wx.previewImage({
       urls: this.data.img_arr
     });
   },
   delete: function (e) {
     var index = e.currentTarget.dataset.index; var img_arr = this.data.img_arr;
     img_arr.splice(index, 1);
     this.setData({
       img_arr: img_arr
     });
   },
//备用地图
   getAddress: function () {
      wx.chooseLocation({
         success: function (res) {
            console.log(res)
            that.setData({
               addressName: res.name,
               addressDetail: res.address,
               latitude: res.latitude,
               longitude: res.longitude,
               inputAddress: true
            })
         },
         fail: function () {
            wx.getSetting({
               success: (res) => {
                  console.log(res);
                  if (!res.authSetting['scope.userLocation']) {
                     wx.showModal({
                        title: '警告',
                        content: '若不授权您的地理信息，将无法正常使用蜂鸟家教，因为教师需要权衡到达上课地点的距离，这是优秀教师是否愿意上课的重要主观因素。\n仅获取您的大致地址，绝不会泄露您的隐私',
                        confirmText: '授权',
                        confirmColor: '#2ba945',
                        cancelColor: '#bdbdbd',
                        success: function (res) {
                           if (res.confirm) {
                              wx.openSetting({
                                 success: (res) => {
                                    res.authSetting = {
                                       "scope.userLocation": true
                                    }
                                 }
                              })

                           } else if (res.cancel) {
                           }
                        }
                     })

                  }
               }

            })



         }
      })
   },

   
  

  
})


